const { createApp, ref } = Vue;
const { ElMessage } = ElementPlus;

// ElMessage挂载全局
window.ElMessage = ElMessage;
const app = createApp({});
app.use(ElementPlus);
app.mount('#reject');

// 获取进度条元素
const progressContainer = document.getElementById('progress-container');
const progressBar = document.getElementById('progress-bar');

// 更新进度条函数
function updateProgress(percent, show = true) {
    if (show) {
        progressContainer.style.display = 'block';
    } else {
        progressContainer.style.display = 'none';
        return;
    }
    
    progressBar.style.width = `${percent}%`;
}

const reportNumbers = ref('');
const selectedAddressIndex = ref('PRD');
const isPRD = ref(true);
const isHeadless = ref(false);

// 从 DOM 获取元素
const switchElement = document.getElementById('switch');
const headlessSwitchElement = document.getElementById('headless-switch');
const reportNumbersTextarea = document.getElementById('orderNumbers'); // 注意：HTML元素ID保持不变，但变量名更改为reportNumbers
const startButton = document.getElementById('startButton');

function handleAddressSwitch() {
    selectedAddressIndex.value = isPRD.value ? 'PRD' : 'UAT';
    // 使用ElMessage向用户提示环境切换状态
    ElMessage.info(`环境已切换至${selectedAddressIndex.value}`);
}
function handleStepsSwitch() {
    console.log(`操作步骤已 ${isHeadless.value ? '显示' : '隐藏'}`);
    // 使用ElMessage向用户提示操作步骤切换状态
    ElMessage.info(`操作步骤已${isHeadless.value ? '显示' : '隐藏'}，${isHeadless.value ? '将展示自动化操作过程' : '将隐藏自动化操作过程'}`);
}

// 绑定事件
switchElement.addEventListener('change', function() {
    isPRD.value = switchElement.checked;
    handleAddressSwitch();
});

headlessSwitchElement.addEventListener('change', function() {
    isHeadless.value = headlessSwitchElement.checked;
    handleStepsSwitch();
});

startButton.addEventListener('click', async function() {
    reportNumbers.value = reportNumbersTextarea.value;
    if (reportNumbers.value.trim() === '') {
        ElMessage.warning('请输入报告号');
        return;
    }

    // 禁用按钮，显示进度条
    startButton.disabled = true;
    updateProgress(10);

    // 使用从预加载脚本暴露的API
    const environment = selectedAddressIndex.value;
    const address = environment === 'PRD' ? 'http://cnapp.sgs.net/gpo-web/#/' : 'http://cnapp-uat.sgs.net/sgsLogin/';
    const reportNumbersArray = reportNumbers.value.split('\n').map((num) => num.trim()).filter((num) => num);

    try {
        // 更新进度条
        updateProgress(20);
        
        const userSettings = await electronAPI.getUserSettings();
        console.log('获取到的用户设置:', userSettings);
        
        // 存储Processing提示的引用，以便后续关闭
        const processingMessage = ElMessage.info({
            message: 'Processing，please wait...',
            duration: 0,  // 设置为0表示不会自动关闭
            showClose: true  // 显示关闭按钮
        });
        
        // 清空之前的结果显示
        const resultContainer = document.getElementById('result-container');
        if (resultContainer) {
            resultContainer.innerHTML = '';
        }
        
        // 更新进度条
        updateProgress(30);
        
        // 在调用脚本前设置进度为30%
        updateProgress(30);
        
        const { success, data, error } = await pluginAPI.runPluginScript({
            pluginName: 'batch-reject',
            script: './core.js',
            args: [address, isHeadless.value, reportNumbersArray, userSettings]
        });
        
        // 脚本执行完成后设置进度为80%
        updateProgress(80);
        
        // 更新进度条
        updateProgress(90);
        
        if (success) {
            // 完成进度条
            updateProgress(100);
            
            // 关闭Processing提示
            if (processingMessage) {
                processingMessage.close();
            }
            
            ElMessage.success({
                message: 'Finished!',
                duration: 3000  // 3秒后自动关闭
            });
            
            // 显示处理结果
            if (data && Array.isArray(data)) {
                displayResults(data);
            }
            
            // 延迟后隐藏进度条
            setTimeout(() => updateProgress(0, false), 1000);
        }
        if (!success) throw new Error(error);
    } catch (error) {
        // 出错时隐藏进度条
        updateProgress(0, false);
        
        // 关闭Processing提示
        if (processingMessage) {
            processingMessage.close();
        }
        
        ElMessage.error({
            message: 'Failed, Please check.',
            duration: 5000,  // 5秒后自动关闭
            showClose: true  // 显示关闭按钮
        });
    } finally {
        // 重新启用按钮
        startButton.disabled = false;
    }
});

// 显示处理结果的函数
function displayResults(results) {
    const resultContainer = document.getElementById('result-container');
    if (!resultContainer) return;
    
    // 清空容器
    resultContainer.innerHTML = '';
    
    // 创建结果标题
    const resultTitle = document.createElement('h3');
    resultTitle.textContent = 'Reject 操作结果';
    resultTitle.style.marginTop = '20px';
    resultContainer.appendChild(resultTitle);
    
    // 显示处理统计信息
    const statsDiv = document.createElement('div');
    statsDiv.style.marginBottom = '15px';
    statsDiv.style.fontSize = '14px';
    
    // 计算成功和失败的数量
    const totalCount = results.length;
    const successCount = results.filter(result => result.success).length;
    const failCount = totalCount - successCount;
    
    // 计算监控数据发送状态统计
    const monitoringSuccessCount = results.filter(result => result.success && result.monitoringStatus === true).length;
    const monitoringFailCount = results.filter(result => result.success && result.monitoringStatus === false).length;
    const monitoringNotRecordedCount = results.filter(result => result.success && !result.hasOwnProperty('monitoringStatus')).length;
    
    // 添加处理结果和监控数据发送状态统计信息
    statsDiv.innerHTML = `
        <div>总共处理: <strong>${totalCount}</strong> 条报告, 成功: <strong style="color: green">${successCount}</strong>, 失败: <strong style="color: red">${failCount}</strong></div>
        <div style="margin-top: 5px;">监控数据: 记录成功: <strong style="color: green">${monitoringSuccessCount}</strong>, 记录失败: <strong style="color: orange">${monitoringFailCount}</strong>, 未记录: <strong style="color: gray">${monitoringNotRecordedCount}</strong></div>
    `;
    resultContainer.appendChild(statsDiv);
    
    // 创建结果表格
    const resultTable = document.createElement('table');
    resultTable.className = 'result-table';
    resultTable.style.width = '100%';
    resultTable.style.borderCollapse = 'collapse';
    resultTable.style.marginTop = '10px';
    
    // 创建表头
    const thead = document.createElement('thead');
    const headerRow = document.createElement('tr');
    ['订单号/客户编号', '报告号', '状态', 'Reject结果', '消息', '记录状态'].forEach(text => {
        const th = document.createElement('th');
        th.textContent = text;
        th.style.padding = '8px';
        th.style.borderBottom = '2px solid #ddd';
        th.style.textAlign = 'left';
        headerRow.appendChild(th);
    });
    thead.appendChild(headerRow);
    resultTable.appendChild(thead);
    
    // 创建表格内容
    const tbody = document.createElement('tbody');
    results.forEach(result => {
        const row = document.createElement('tr');
        
        // 订单号
        const orderNoCell = document.createElement('td');
        orderNoCell.textContent = result.orderNo || '-';
        orderNoCell.style.padding = '8px';
        orderNoCell.style.borderBottom = '1px solid #ddd';
        row.appendChild(orderNoCell);
        
        // 报告号
        const reportNoCell = document.createElement('td');
        reportNoCell.textContent = result.reportNo || '-';
        reportNoCell.style.padding = '8px';
        reportNoCell.style.borderBottom = '1px solid #ddd';
        row.appendChild(reportNoCell);
        
        // 状态
        const statusCell = document.createElement('td');
        statusCell.textContent = result.status || '-';
        statusCell.style.padding = '8px';
        statusCell.style.borderBottom = '1px solid #ddd';
        row.appendChild(statusCell);
        
        // Reject结果
        const successCell = document.createElement('td');
        successCell.textContent = result.success ? '成功' : '失败';
        successCell.style.padding = '8px';
        successCell.style.borderBottom = '1px solid #ddd';
        successCell.style.color = result.success ? 'green' : 'red';
        successCell.style.fontWeight = 'bold';
        row.appendChild(successCell);
        
        // 消息
        const messageCell = document.createElement('td');
        messageCell.textContent = result.message || '-';
        messageCell.style.padding = '8px';
        messageCell.style.borderBottom = '1px solid #ddd';
        row.appendChild(messageCell);
        
        // 监控记录状态
        const monitoringCell = document.createElement('td');
        if (result.success) {
            if (result.hasOwnProperty('monitoringStatus')) {
                monitoringCell.textContent = result.monitoringStatus ? '记录成功' : '记录失败';
                monitoringCell.style.color = result.monitoringStatus ? 'green' : 'orange';
                monitoringCell.title = result.monitoringMessage || '';
            } else {
                monitoringCell.textContent = '未记录';
                monitoringCell.style.color = 'gray';
            }
        } else {
            monitoringCell.textContent = '不适用';
            monitoringCell.style.color = 'gray';
        }
        monitoringCell.style.padding = '8px';
        monitoringCell.style.borderBottom = '1px solid #ddd';
        monitoringCell.style.fontWeight = 'bold';
        row.appendChild(monitoringCell);
        
        tbody.appendChild(row);
    });
    resultTable.appendChild(tbody);
    
    resultContainer.appendChild(resultTable);
}